// 引入动态路由  常规路由
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 通过后台获取的menuList和本地的asyncRoutes进行比对，返回存在的路由
 * @param routes   需要动态设置的asyncRoutes
 * @param menuList  通过后台接口获取的用户菜单列表
 */
export function filterAsyncRoutes(routes, menuList) {
  const res = []
  routes.forEach(item => {
    menuList.forEach(menu => {
      if (item.path === menu.path) {
        const tmp = { ... item }
        tmp.children = []
        if (menu.children && menu.children.length > 0) {
          tmp.children = filterAsyncRoutes(item.children, menu.children)
        }
        res.push(tmp)
      }
    })
  })
  return res
}

/**
 *左侧栏的路由显示由后台权限控制
 *vuex管理左侧菜单路由
*/
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 生成需要添加的路由
  generateRoutes({ commit }, menuList) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, menuList)
      // 404 page must be placed at the end !!!
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
